package com.example.serverdemo.util;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import com.example.serverdemo.constant.RSAConstant;
import org.apache.commons.codec.binary.Base64;

public class RSACipher {

	public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";

	public static final String CHARSET = "utf-8";
	/**
	 * RSA解密方法
	 *
	 * @param str        待解密密文
	 * @param privateKey 私钥
	 * @return 解密后的明文
	 */
	public static String decrypt(String str, String privateKey) throws Exception {
		//64位解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
		System.out.println(inputByte.length);
		//base64编码的私钥
		byte[] decoded = Base64.decodeBase64(privateKey);
		RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
				.generatePrivate(new PKCS8EncodedKeySpec(decoded));
		Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, priKey);
		String outStr = new String(cipher.doFinal(inputByte));
		return outStr;
	}

	/**
	 * RSA公钥加密
	 *
	 * @param str       加密字符串
	 * @param publicKey 公钥
	 * @return 密文
	 * @throws Exception 加密过程中的异常信息
	 */
	public static String encrypt(String str, String publicKey) throws Exception {
		//base64编码的公钥
		byte[] decoded = Base64.decodeBase64(publicKey);
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
		//RSA加密
		Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
	}


/*	public static void main(String[] args) {
		// 用于测试RsaCipher工具类， 公私钥从EncryptUtil和DecryptUtil中获取
		try {
            String rawAes = "我是aes";
            String encryptAes = RSACipher.encrypt(rawAes, RSAConstant.encPk);
            System.out.println("加密后的AES:"+encryptAes);
            String decryptAes = RSACipher.decrypt(encryptAes, RSAConstant.encSk);
            System.out.println("解密后的AES:"+decryptAes);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}*/

}
